package com.saifan.wyy_ov.ui.communitycenter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.google.gson.Gson;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.common.BaseFragment;
import com.saifan.wyy_ov.common.IconText;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.ui.home.FeedbackActivity;
import com.saifan.wyy_ov.ui.onlishop.MyOrderActivity;
import com.saifan.wyy_ov.ui.property.DecorationApplyRecordActivity;
import com.saifan.wyy_ov.ui.property.EngagedServiceRecordActivity;
import com.saifan.wyy_ov.ui.user.LoginActivity;
import com.saifan.wyy_ov.ui.view.CircleImageView;
import com.saifan.wyy_ov.ui.view.NoScrollListView;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.ImgUtil;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import lomasky.ma.httpUtils.HttpUtil;
import lomasky.ma.utils.SharedPrefUtil;
import lomasky.ma.xui.BaseRecyclerViewAdapter;
import lomasky.ma.xui.BaseViewHolder;
import lomasky.ma.xui.ItemDivider;
import lomasky.ma.xui.RecyclerViewAdapter;
import lomasky.ma.xui.WrapContentGirdLayoutManager;
import lomasky.ma.xui.WrapContentLineaLayoutManager;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-05-05 14:41
 * @descrption 业主中心
 */
public class CommunitycenterFragment extends BaseFragment implements View.OnClickListener {

    private static final int USER_INFO_CHANGE = 123;
    RoomInfoBean roomInfoBean;
    private RecyclerView recyclerView1;
    private RecyclerViewAdapter<IconText> adapter1;
    private NoScrollListView recyclerView2;
    private CommonAdapter<IconText> adapter2;
    private RecyclerView recyclerView3;
    private RecyclerViewAdapter<IconText> adapter3;
    private LinearLayout selectroom;
    private com.saifan.wyy_ov.ui.view.CircleImageView photo;
    private TextView userName;
    private TextView address;
    private LinearLayout roominformation;
    private LinearLayout userinfo;
    private TextView logout;
    private boolean isDownloading = false;

    public static CommunitycenterFragment newInstance(int position) {
        CommunitycenterFragment fragment = new CommunitycenterFragment();
        Bundle args = new Bundle();
        args.putInt("position", position);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onClick(View v) {
        if (getRoomInfoBean().getUserType() == 3) {
            ToastUtil.showToast(getActivity(), "您的权限不能进行此操作");
            return;
        }

        if (v == userinfo) {
            startActivityForResult(new Intent(getContext(), UserInfoActivity.class), USER_INFO_CHANGE);

        } else if (v == selectroom) {
            startActivity(new Intent(getContext(), RoomSelectActivity.class));

        } else if (v == roominformation) {
            startActivity(new Intent(getContext(), RoominformationActivity.class));

        } else if (v == logout) {
            SharedPrefUtil.remove(getContext(), "Password");
            Intent intent = new Intent(getContext(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case USER_INFO_CHANGE:

                roomInfoBean = new Gson().fromJson(SharedPrefUtil.getString(getActivity(), "roomInfo", ""), RoomInfoBean.class);
                if (!StringUtil.isNullOrEmpty(roomInfoBean.getWYKHDA_TXLJ())) {
                    ImgUtil.DisPlayImg(roomInfoBean.getWYKHDA_TXLJ(), photo, getActivity());
                }
                userName.setText(roomInfoBean.WYKHDA_LC);
                address.setText(roomInfoBean.XMDA_XMMC + getRoomInfoBean().getWYFJDA_FJMC());
        }

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        roomInfoBean = getRoomInfoBean();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_communitycenter, container, false);
        this.logout = (TextView) view.findViewById(R.id.logout);
        this.userinfo = (LinearLayout) view.findViewById(R.id.userinfo);
        this.roominformation = (LinearLayout) view.findViewById(R.id.roominformation);
        this.address = (TextView) view.findViewById(R.id.address);
        this.userName = (TextView) view.findViewById(R.id.userName);
        this.photo = (CircleImageView) view.findViewById(R.id.photo);
        this.selectroom = (LinearLayout) view.findViewById(R.id.select_room);

        userName.setText(getRoomInfoBean().WYKHDA_LC);
        address.setText(getRoomInfoBean().XMDA_XMMC + getRoomInfoBean().getWYFJDA_FJMC());
        this.selectroom.setOnClickListener(this);
        this.roominformation.setOnClickListener(this);
        this.userinfo.setOnClickListener(this);
        this.logout.setOnClickListener(this);



        if (!StringUtil.isNullOrEmpty(getRoomInfoBean().getWYKHDA_TXLJ())) {
            ImgUtil.DisPlayImg(getRoomInfoBean().getWYKHDA_TXLJ(), photo, getActivity());
        }
        //-------------------------1
        recyclerView1 = (RecyclerView) view.findViewById(R.id.recyclerView1);
        recyclerView1.setLayoutManager(new WrapContentGirdLayoutManager(getContext(), 4));
        adapter1 = new RecyclerViewAdapter<IconText>(getContext(), R.layout.icon_text_v) {
            @Override
            public void onBind(BaseViewHolder holder, IconText item, int position) {
                holder.setText(R.id.text, item.text).setImage(R.id.icon, item.icon);

            }
        };
        recyclerView1.setAdapter(adapter1);
        adapter1.add(new IconText(R.mipmap.myorder, getString(R.string.my_order)));
        adapter1.add(new IconText(R.mipmap.mymessage, getString(R.string.my_message)));
        adapter1.add(new IconText(R.mipmap.myenshrine, getString(R.string.my_collect)));
        adapter1.add(new IconText(R.mipmap.jiluchaxun, getString(R.string.record_query)));

        adapter1.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                switch (position) {

                    //我的订单
                    case 0:
                        Intent intent1 = new Intent();
                        intent1.setClass(getContext(), MyOrderActivity.class);
                        startActivity(intent1);
                        break;

                    // 我的消息
                    case 1:
                        Intent intent3 = new Intent();
                        intent3.setClass(getContext(), MyMessageActivity.class);
                        startActivity(intent3);
                        break;
                    //我的收藏
                    case 2:
                        Intent intent4 = new Intent();
                        intent4.setClass(getContext(), MyenshrineActivity.class);
                        startActivity(intent4);
                        break;

                    //我的缴费记录
                    case 3:
                        Intent intent5 = new Intent();
                        intent5.setClass(getContext(), PaythefeesActivity.class);
                        startActivity(intent5);
                        break;


                    default:
                        break;
                }

            }
        });
//-------------------------2
        recyclerView2 = (NoScrollListView) view.findViewById(R.id.recyclerView2);
//        recyclerView2.setLayoutManager(new WrapContentLineaLayoutManager(getContext()));
//        recyclerView2.addItemDecoration(new ItemDivider(getContext()));

        List<IconText> list= new ArrayList<>();
        list.add(new IconText(R.mipmap.mydecoration, getString(R.string.my_decoration_apply)));
        list.add(new IconText(R.mipmap.engagedservice, getString(R.string.engaged_service_recoder)));
        list.add(new IconText(R.mipmap.rentalandsales, getString(R.string.my_rental_record)));
        list.add(new IconText(R.mipmap.fleamarket, getString(R.string.fleamarket)));
        list.add(new IconText(R.mipmap.introduce, "关于物业云"));
        list.add(new IconText(R.mipmap.user_agreement, "用户协议"));
        list.add(new IconText(R.mipmap.feedback, "意见反馈"));
        list.add(new IconText(R.mipmap.version_updating, "版本更新"));
        list.add(new IconText(R.mipmap.share, "分享软件"));

        adapter2 = new CommonAdapter<IconText>(getContext(),list, R.layout.icon_text_h) {
            @Override
            public void convert(ViewHolderHelper helper, IconText item) {
                helper.setText(R.id.text, item.text );
                helper.setImageResource(R.id.icon, item.icon);
               LinearLayout linearLayout=  helper.getView(R.id.layout) ;
                linearLayout.setClickable(false);

            }


        };

        recyclerView2.setAdapter(adapter2);


        recyclerView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {

                    //我的装修申请
                    case 0:
                        Intent intent8 = new Intent();
                        intent8.setClass(getContext(), DecorationApplyRecordActivity.class);
                        startActivity(intent8);
                        break;
                    //我的特约服务
                    case 1:
                        Intent intent9 = new Intent();
                        intent9.setClass(getContext(), EngagedServiceRecordActivity.class);
                        startActivity(intent9);
                        break;
                    //我的租售消息
                    case 2:
                        Intent intent10 = new Intent();
                        intent10.setClass(getContext(), MyRentalRecordActivity.class);
                        startActivity(intent10);
                        break;
                    //跳蚤市场
                    case 3:
                        Intent intent11 = new Intent();
                        intent11.setClass(getContext(), MyFleaMarketRecordActivity.class);
                        startActivity(intent11);
                        break;
                    //关于
                    case 4:
                        startActivity(new Intent(getContext(), AboutActivity.class));
                        break;
                    //用户协议
                    case 5:
                        startActivity(new Intent(getContext(), ArgeenActivity.class));



                        break;

                    case 6:
                        startActivity(new Intent(getContext(), FeedbackActivity.class));
                        break;
                    case 7:
                        HttpUtil.checkVesionNoDialog(  getString(R.string.app_name), new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                ToastUtil.showToast(getActivity(), getString(R.string.network_error));

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                String resp = response.body().string();
                                LogUtil.d(resp);

                                try {
                                    JSONObject jsonObject = new JSONObject(resp);
                                    if (jsonObject.getInt("Code") == 200) {
                                        String content = jsonObject.getString("Content");
                                        if (!TextUtils.isEmpty(content)) {
                                            PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), PackageManager.GET_META_DATA);
//
                                            AppVersion appVersion = new Gson().fromJson( content, AppVersion.class);
                                            if (appVersion != null) {
                                                String loaclVersionName =   pInfo.versionName  ;
                                                String serverVersionName =  appVersion.getVersion() ;
                                                if (!TextUtils.isEmpty(loaclVersionName)&&!TextUtils.isEmpty(serverVersionName) &&serverVersionName.compareTo(loaclVersionName)>0  ) {
                                                    Message msg = new Message();
                                                    msg.obj = appVersion;
                                                    msg.what = 0;
                                                    handler.sendMessage(msg);

                                                } else {


                                                }


                                            } else {
                                                handler.sendEmptyMessage(1);


                                            }

                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                } catch (PackageManager.NameNotFoundException e) {


                                }


                            }
                        });

                        break;
                    case 8:
                        try {
                            PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), PackageManager.GET_META_DATA);
                            String appName = "";
                            appName = getActivity().getPackageManager().getApplicationLabel(pInfo.applicationInfo).toString();
                            File apkFile = new File(pInfo.applicationInfo.sourceDir);

                            if (!apkFile.exists()) {
                                toast( "文件不存在");
                                return;
                            }


                            Intent intent = new Intent(Intent.ACTION_SEND);
                            intent.setType("*/*");
                            intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.app_name));


                            Uri uri;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                uri = FileProvider.getUriForFile(getActivity()  , "com.saifan.wyy_ov.fileprovider", apkFile);
                            } else {
                                uri = Uri.fromFile(apkFile);
                            }

                            intent.putExtra(Intent.EXTRA_STREAM, uri);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();

                        }
                        break;
                    default:
                        break;

                }

            }
        });


        return view;
    }

    private void toast(String m) {
        ToastUtil.showToast(getActivity(),m);

    }


    private AppVersion newVersion;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {

                if (isDownloading) {
                    ToastUtil.showToast(getActivity(), "已开始下载，请等待完成");
                } else {

                    newVersion = (AppVersion) msg.obj;
                    showDownDailog(newVersion);
                }
            } else {
                ToastUtil.showToast(getActivity(), "已是最新版本");
            }
        }
    };

    private void showDownDailog(final AppVersion appVersion) {
        AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle("是否更新到" + appVersion.getVersion() + "?")
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        download(appVersion);

                    }


                })
                .setPositiveButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create();
        dialog.show();

    }


    @Override
    public void onPause() {
        super.onPause();
    }

    private void download(AppVersion appVersion) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://www.sfwyy.com" + appVersion.getPath()));
        request.setMimeType("application/vnd.android.package-archive");
        DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
        request.setDestinationInExternalFilesDir(getActivity(), null, getString(R.string.app_name) + ".apk");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);


        isDownloading = true;
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        sp.edit().putLong(PrefsConsts.DOWNLOAD_APK_ID_PREFS, downloadManager.enqueue(request)).apply();

    }
}
